package com.sun.dream.fish.controller;

import com.sun.dream.fish.service.IFileService;
import com.sun.dream.fish.util.ResponseUtil;
import com.sun.dream.fish.vo.ResultVO;
import com.sun.dream.fish.vo.test.TestVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
public class TestController {

    @PostMapping(value = "/test")
    public ResultVO<String> excelUpload(@RequestBody() TestVO newName) {
        return new ResultVO<>(newName.getNewName() + ", 接受成功", 200);
    }

    @Autowired
    IFileService fileService;

    @PostMapping(value = "/test/upload")
    public ResultVO excelUpload(@RequestPart("file") MultipartFile file, @RequestPart("fileName") String fileName) {
        if (file == null) {
            return ResponseUtil.fail("请选择文件上传!!!");
        }
        return fileService.storeExcelFile(file, fileName) ? ResponseUtil.ok("文件上传成功") : ResponseUtil.fail("文件上传失败");
    }

    @GetMapping(value = "/test/download")
    public ResponseEntity<FileSystemResource> excelDownload(@RequestParam(value = "fileName") String fileName) {
        FileSystemResource fileSystemResource;
        try {
            fileSystemResource = fileService.downloadExcelFile(fileName);
        } catch (Exception e) {
            log.error("[TestController.excelDownload], ", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (fileSystemResource == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment;", fileSystemResource.getFilename());
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileSystemResource);
    }
}
